package com.hxzy.controller.mobile.login;

import com.hxzy.common.constans.RedisConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.TokenService;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.admin.login.req.AdminLoginReq;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.controller.mobile.login.req.MobileLoginReq;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.service.AdminLoginService;
import com.hxzy.service.ContamerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/7/19 16:44
 * @Version 1.0
 */
@Api(tags = "手机端-登录")
@RestController
@RequestMapping(value = "/mobile")
public class MobileLoginController {

    @Autowired
    private ContamerService contamerService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 令牌加密、解密操作
     */
    @Autowired
    private TokenService tokenService;


    /**
     * 登录 (如何实现同一个用户账户只允许输入错误次数3次，时间范围在30分钟之内，超过3次，账户禁定30分钟)
     *      同一个账户只允许登录一次(如何来实现?)
     * @param req
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R<String> login(@RequestBody @Valid MobileLoginReq req) {
        String redisKey = RedisConstans.getRedisKey(RedisConstans.CAPTCHA_KEY, req.getUuid());
        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);
        //删除验证码
        this.redisTemplate.delete(redisKey);
        if (Objects.isNull(redisValue)) {
            return R.build(AckCode.SMS_CODE_OVERTIME);
        }

        if (!redisValue.toString().equalsIgnoreCase(req.getCode())) {
            return R.build(AckCode.SMS_CODE_WRONG);
        }

        //登录
        MobileLoginResp mobileLoginResp=this.contamerService.login(req);

        //管理员对象存储到redis中，再返回令牌，再令牌进行jwt加密
        String jwtToken=this.tokenService.createMobileJwtToken(mobileLoginResp);

        return R.okHasData(jwtToken);
    }


    @ApiOperation(value = "获取登录信息")
    @GetMapping(value = "/user/info")
    public R<MobileLoginResp> userInfo(){
        return R.okHasData( WaimaiThreadLocal.mobileLoginThreadLocal.get());
    }

    @ApiOperation(value = "登出")
    @PostMapping(value = "/logout")
    public R<String> logout(){
        MobileLoginResp current =WaimaiThreadLocal.mobileLoginThreadLocal.get();
        this.tokenService.removeMobileRedisLoginVO(current.getToken());
        return R.ok();
    }


}
